
import sys
from PyQt5.QtWidgets import QApplication, QMainWindow,QMenu, QAction
from ui.mainwindow import Ui_MainWindow
from PyQt5.QtCore import Qt, QObject, pyqtSignal
from PyQt5.QtGui import QStandardItemModel, QStandardItem
import json

class NodeEditor(QObject):
    nodeSelected = pyqtSignal(QStandardItem)

    def __init__(self, treeView, sqlQuery, keyFields, excludeFields):
        super().__init__()
        self.sqlQuery = sqlQuery
        self.keyFields = keyFields
        self.excludeFields = excludeFields
        self.treeView = treeView
        self.model = QStandardItemModel()
        self.model.setHorizontalHeaderLabels(['节点名称'])
        self.treeView.setModel(self.model)
        self.treeView.clicked.connect(self.on_node_clicked)
        
        # 创建不可删除的根节点
        self.root_node = QStandardItem("根节点")
        self.model.appendRow(self.root_node)

        # 加载 JSON 数据
        with open("testdata.json", "r", encoding="utf-8") as f:
            self.node_data = json.load(f)

    def on_node_clicked(self, index):
        print(index)
        node = self.model.itemFromIndex(index)
        if node:
            node_name = node.text()
            node_info = self.node_data.get(node_name, {})
            sql_query = node_info.get("sqlQuery","")
            key_fields = node_info.get("keyFields","")
            exclude_fields = node_info.get("excludeFields","")
            self.sqlQuery.setText(sql_query)
            self.keyFields.setText(key_fields)
            self.excludeFields.setText(exclude_fields)

            self.nodeSelected.emit(node)

    def add_node(self, parent_node=None):
        print(parent_node)
        print(parent_node.text())
        if parent_node is None:
            parent_node = self.model.invisibleRootItem()
        new_node = QStandardItem("新节点")
        parent_node.appendRow(new_node)

    def delete_node(self, node):
        # 根节点不可删除
        print(node)
        if node and node != self.root_node:
            parent = node.parent() or self.model.invisibleRootItem()
            parent.removeRow(node.row())




class MyMainWindow(QMainWindow, Ui_MainWindow):
    def __init__(self, parent=None):
        super(MyMainWindow, self).__init__(parent)
        self.setupUi(self)

        # 设置节点树与内容页面比例
        self.splitter.setStretchFactor(0, 1)
        self.splitter.setStretchFactor(1, 2)

        # treeView
        self.treeView.setContextMenuPolicy(Qt.CustomContextMenu)  # 允许右键菜单
        self.treeView.customContextMenuRequested.connect(self.show_context_menu)

        # 节点编辑器
        self.node_editor = NodeEditor(self.treeView, self.textEdit, self.lineEdit_6, self.lineEdit_7)

    def show_context_menu(self, position):
        index = self.treeView.indexAt(position)
        if not index.isValid():
            return

        node = self.node_editor.model.itemFromIndex(index)
        menu = QMenu()
        
        # 添加节点动作
        add_action = QAction("添加子节点", self)
        add_action.triggered.connect(lambda: self.node_editor.add_node(node))
        
        # 删除节点动作（根节点不可用）
        del_action = QAction("删除节点", self)
        if node == self.node_editor.root_node:
            del_action.setEnabled(False)
        else:
            del_action.triggered.connect(lambda: self.node_editor.delete_node(node))
        
        menu.addAction(add_action)
        menu.addAction(del_action)
        menu.exec_(self.treeView.viewport().mapToGlobal(position))


if __name__ == "__main__":
    app = QApplication(sys.argv)
    window = MyMainWindow()
    window.show()
    sys.exit(app.exec_())
